package com.dongdongshop.controller;

import com.dongdongshop.data.Result;
import com.dongdongshop.enums.ResultEnum;
import com.dongdongshop.pojo.TbSeckillGoods;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.SeckillService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.dc.pr.PRError;

import java.util.List;

@RequestMapping("/seckillController")
@Controller
public class SeckillController {
    @DubboReference
    private SeckillService seckillService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/seckillIndex")
    public String seckillIndex(){
        return "seckill-index";
    }

    //缓存预热
    @RequestMapping("prepareHot")
    @ResponseBody
    public String prepareHot(){
        seckillService.prepareHot();
        return "ok";
    }

    @RequestMapping("/listSeckill")
    @ResponseBody
    public Result listSeckill(){
        List<TbSeckillGoods> list = seckillService.listSeckill();
        return Result.OK().setData(list);
    }

    @RequestMapping("/seckillItem/{id}")
    public String seckillItem(@PathVariable("id") Long id, Model model){
        TbSeckillGoods seckillGoods =  seckillService.selectSeckillById(id);

        model.addAttribute("seckillGoods",seckillGoods);

        return "seckill-item";
    }
    @RequestMapping("/createOrder")
    @ResponseBody
    public Result createOrder(Long goodsId){
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null){
            return Result.response(ResultEnum.ACCOUNT_NOT_LOGIN);
        }
        try {
            seckillService.createOrder(goodsId,user);
        } catch (Exception e) {
            return Result.response(ResultEnum.SALE_OVER);
        }
        return Result.OK();
    }

    @RequestMapping("/getOrderId")
    @ResponseBody
    public Result getOrderId(){
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null){
            return Result.response(ResultEnum.ACCOUNT_NOT_LOGIN);
        }
        Long goodsId = (Long) redisTemplate.boundValueOps("order" + user.getUsername()).get();

        return Result.OK().setData(goodsId+"");
    }
}
